package redis_init

import (
	"context"
	"github.com/redis/go-redis/v9"
	"go_server/login_server/util"
	"go_server/zinx/zconstant"
	"go_server/zinx/zlog"
)

var (
	game_redis *redis.Client
	center_redis *redis.Client
	login_redis *redis.Client
	subscribe_redis *redis.Client
)

type redisConfig struct {
	GameRedis zconstant.RedisClient `mapstructure:"game";json:"gameRedis"`
	CenterRedis zconstant.RedisClient `mapstructure:"center";json:"centerRedis"`
	LoginRedis zconstant.RedisClient `mapstructure:"login";json:"loginRedis"`
	SubscribeRedis zconstant.RedisClient `mapstructure:"subscribe";json:"subscribeRedis"`
}

var redisClient *redisConfig

func Init() {
	viper, _ := util.CreateConfig("redis")
	if err := viper.Unmarshal(&redisClient); err != nil {
		zlog.Panicf("unable to decode into struct, %v", err)
	}

	game_redis = createRedisClient(redisClient.GameRedis.Addr, redisClient.GameRedis.Password,
		redisClient.GameRedis.SelectDb, "GAME")

	center_redis = createRedisClient(redisClient.CenterRedis.Addr, redisClient.CenterRedis.Password,
		redisClient.CenterRedis.SelectDb, "CENTER")

	login_redis = createRedisClient(redisClient.LoginRedis.Addr, redisClient.LoginRedis.Password,
		redisClient.LoginRedis.SelectDb, "LOGIN")

	subscribe_redis = createRedisClient(redisClient.SubscribeRedis.Addr, redisClient.SubscribeRedis.Password,
		redisClient.SubscribeRedis.SelectDb, "SUBSCRIBE")
}

func GetGameRedisClient() *redis.Client {
	return game_redis
}

func GetSubscribeRedisClient() *redis.Client {
	return subscribe_redis
}

func createRedisClient(addr string, pass string, db int, name string) *redis.Client {
	cli := redis.NewClient(&redis.Options{
		Addr: addr,
		Password: pass,
		DB: db,
		ClientName: name,
	})

	if err := cli.Ping(context.Background()).Err(); err != nil {
		zlog.Panicf("connect to %s redis %d failed %v", name, db, err)
	} else {
		zlog.Infof("connect to %s redis %d success!!!\n\n", name, db)
	}

	return cli
}

func CloseRedisClient() {
	if game_redis != nil {
		game_redis.Close()
	}

	if center_redis != nil {
		center_redis.Close()
	}

	if login_redis != nil {
		login_redis.Close()
	}

	if subscribe_redis != nil {
		subscribe_redis.Close()
	}
}
